package com.dycong.common.IO.netty.ssl.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by dycong on 2017/4/5.
 */
public class NettySocketClient {
    private NioEventLoopGroup nioEventLoopGroup = null;
    private SocketAddress remoteAddress = new InetSocketAddress("127.0.0.1", 12121);
    AtomicBoolean isActive = new AtomicBoolean(false);
    ChannelFuture future;

    public void start() {
        if (isActive.compareAndSet(false, true)) {
            nioEventLoopGroup = nioEventLoopGroup == null ? new NioEventLoopGroup() : nioEventLoopGroup;
            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(nioEventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .handler(new SecureClientInitializer());

            try {
                future = bootstrap.connect(remoteAddress).sync();
                future.channel().closeFuture().sync();
            } catch (InterruptedException e) {

            } finally {
                try {
                    if (future != null)
                        nioEventLoopGroup.shutdownGracefully().sync();
                } catch (InterruptedException e) {
                }
                isActive.compareAndSet(true, false);
            }

        }
    }

    public void sendMsg(String msg) {
        future.channel().writeAndFlush(msg);
    }

    public static void main(String[] args) {
        NettySocketClient client = new NettySocketClient();
        client.start();

    }

}
